package com.consumer.config;

import com.alibaba.fastjson.JSON;
import com.consumer.entity.Order;
import com.consumer.service.OrderService;
import com.consumer.utils.RedisUtil;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @Description
 * @Author youxin
 * @Version V1.0.0
 * @Since 1.0
 * @Date 2021/11/18
 */
//@Component
public class OrderMessageListenner implements MessageListenerConcurrently {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private OrderService orderService;


    @Override
    public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> list, ConsumeConcurrentlyContext consumeConcurrentlyContext) {
        for (MessageExt message:list) {
            String body=new String(message.getBody(), StandardCharsets.UTF_8);
            Order order = JSON.parseObject(body, Order.class);
            try{
                //TODO 调用取消订单方法之前 应当确保不能有支付等操作  通过redis保证取消订单的幂等性
                boolean lock = redisUtil.getLock(order.getId(), 60000);
                //TODO 获取锁成功 进行取消订单操作
                if(lock){
                    orderService.cancelOrder(order);
                }
            }catch (Exception e){
                //TODO 出现异常进行重试
                return ConsumeConcurrentlyStatus.RECONSUME_LATER;
            }finally {
                //TODO 释放redis 锁
                redisUtil.releaseLock(order.getId());
            }
        };
        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }
}
